package com.gbs.info2;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import com.gbs.info2.obj.VehicleMobile;
import com.gbs.info2.tools.DatabaseHelper;
import com.gbs.info2.tools.WShelper;

public class VehicleList extends ListActivity {

	private ProgressDialog m_ProgressDialog = null;
	private ArrayList<VehicleMobile> vehicleMobiles = null;
	private VehicleAdapter m_adapter;
	ArrayAdapter<String> spinnerAdapter;
	private Runnable viewVehicles, runUpdate;
	private Spinner locFilter;
	private String tmpWhereCause;
	private DatabaseHelper databaseHelper;
	private Context context;
	ArrayList<String> locationTypeSpinnerList;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vehiclelist);
		this.context = this;
		databaseHelper = new DatabaseHelper(this);
		tmpWhereCause = getString(R.string.all);
		vehicleMobiles = new ArrayList<VehicleMobile>();
		this.m_adapter = new VehicleAdapter(this, R.layout.row, vehicleMobiles);
		setListAdapter(this.m_adapter);
		spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, new ArrayList<String>());
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		locFilter = (Spinner) findViewById(R.id.locFilter);
		locationTypeSpinnerList = new ArrayList<String>();
		locFilter.setAdapter(spinnerAdapter);
		
		locFilter.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parentView,View selectedItemView, int position, long id) {
				if (!tmpWhereCause.equals(locFilter.getSelectedItem().toString())) {
					tmpWhereCause = locFilter.getSelectedItem().toString();
					new Thread(null, viewVehicles, "MagentoBackground").start();
				}
			}
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		viewVehicles = new Runnable() {
			public void run() {
				getVehicles(getLocationWhereCause());
			}
		};
		Thread thGetVehicle = new Thread(null, viewVehicles,"MagentoBackground");
		thGetVehicle.start();
		m_ProgressDialog = ProgressDialog.show(this,getString(R.string.waiting), getString(R.string.dbLoading),true);

	runUpdate = new Runnable() {
		public void run() {
				WShelper wShelper = new WShelper(context);
				ArrayList<VehicleMobile> vehicleMobiles = wShelper.getVehicleList();
				if (vehicleMobiles!=null){
					//ak je spojenie aktivne zmazu sa stare data
					databaseHelper.deleteAll();
					try {
							for (VehicleMobile v : vehicleMobiles) {
								databaseHelper.insert(v);
							}
						m_ProgressDialog.dismiss();
						//toast oznamenie o uspesnom ukonceni update
						runOnUiThread(new Runnable() {
						    public void run() {
						    	Toast.makeText(context,context.getText(R.string.endUpdateOK), 2000).show();
						    }
						});
						new Thread(null, viewVehicles, "MagentoBackground").start();
					} catch (Exception e) {
						Toast.makeText(context, e.getMessage(), 10000).show();
					}
				}else {
					m_ProgressDialog.dismiss();
					//toast oznamenie o neuspesnom ukonceni update
					runOnUiThread(new Runnable() {
					    public void run() {
					    	Toast.makeText(context,context.getText(R.string.connectionProblem), 3000).show();
					    }
					});
					
				}
		}
	};
	//bundle pre identifikaciu autoupdate
	try {
		Bundle bundle = getIntent().getExtras();
		String autoUpdateStr = (String) bundle.get("autoUpdate");
		if ((autoUpdateStr!=null) && autoUpdateStr.equals("1")){
			Toast.makeText(context, getString(R.string.runAutoApdate), 2000).show();
			new Thread(null, runUpdate,"thUpdate").start();
		}
		//vysledkom je ze pri otoceni display sa auto update uz nespusti
		getIntent().removeExtra("autoUpdate");
	}catch (NullPointerException e) {
		//bunndle null, pre pripad ked je activata volana za behu aplikacie z inej ako startovacej activity - nedochadza k updatu
	}
	}

	private Runnable returnRes = new Runnable() {
		public void run() {
			if (vehicleMobiles != null && vehicleMobiles.size() > 0) {
				m_adapter.clear();
				m_adapter.notifyDataSetChanged();
				for (int i = 0; i < vehicleMobiles.size(); i++)
					m_adapter.add(vehicleMobiles.get(i));
			}
			m_ProgressDialog.dismiss();
			m_adapter.notifyDataSetChanged();
		}
	};
	
	private Runnable updateSpinner = new Runnable() {
		public void run() {

			spinnerAdapter.clear();
			spinnerAdapter.notifyDataSetChanged();
			for (int i = 0; i < locationTypeSpinnerList.size();i ++){
				spinnerAdapter.add(locationTypeSpinnerList.get(i));
			}
			//m_ProgressDialog.dismiss();
			spinnerAdapter.notifyDataSetChanged();
		}
	};

	private void getVehicles(String locationWhereCause) {
		try {
			vehicleMobiles = new ArrayList<VehicleMobile>();
			//databaseHelper = new DatabaseHelper(this);
			vehicleMobiles = databaseHelper.selectAll(locationWhereCause);
			if (locationWhereCause == null){
				setLocationTypes(vehicleMobiles);
			}
			Log.i("ARRAY", "" + vehicleMobiles.size());
		} catch (Exception e) {
			Log.e("BACKGROUND_PROC", e.getMessage());
		}
		runOnUiThread(returnRes);
	}

	private String getLocationWhereCause() {
		String cause = "locationType=";
		try {
			if (locFilter == null)
				return null;
			if (locFilter.getSelectedItem().toString() == getString(R.string.all)) {
				return null;
			}
			cause += "'" + locFilter.getSelectedItem().toString() + "'";
			return cause;
		} catch (Exception e) {
			return null;
		}
	}

	private void setLocationTypes(ArrayList<VehicleMobile> vehicleMobiles) {
			locationTypeSpinnerList.clear();
			locationTypeSpinnerList.add(getString(R.string.all));
			for (VehicleMobile v : vehicleMobiles) {
				for (int i = 0; i < locationTypeSpinnerList.size(); i++) {
					if (v.getLocationType().equals(locationTypeSpinnerList.get(i)))
						break;
					if (i == locationTypeSpinnerList.size() - 1)
						locationTypeSpinnerList.add(v.getLocationType());
				}
			}
			//samotny update adaptera
			runOnUiThread(updateSpinner);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intentDetailView = new Intent(this, DetailView.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("vehicleMobile", vehicleMobiles.get(position));
		intentDetailView.putExtras(bundle);
		locFilter.setSelected(true);
		this.startActivity(intentDetailView);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.vehiclelistmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.mnuUpdate:
			m_ProgressDialog = ProgressDialog.show(this,getString(R.string.waiting), getString(R.string.wsLoading),true);
			 new Thread(null, runUpdate,"thUpdate").start();
			return true;
		case R.id.mnuSettings:
			finish();
			startActivity(new Intent (this, Settings.class));
			return true;
		case R.id.mnuAbout:;
			startActivity(new Intent(this, About.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.exitConfirm))
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setCancelable(false)
				.setPositiveButton(getString(R.string.yesAnswer),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								finish();
								System.exit(0);
							}
						})
				.setNegativeButton(getString(R.string.noAnswer),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}
}


